﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Jayden.Dll.Updater
{
	public class SoftwareVersionInformation
	{
		private string m_SoftwareName;
		private string m_SoftwareVersion;
		private List<FileVersionInformation> m_Files = new List<FileVersionInformation>();

		public SoftwareVersionInformation(string directoryPath, string name, string version)
		{
			m_SoftwareName = name;
			m_SoftwareVersion = version;
			string[] files = Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories);
			foreach (string file in files)
			{
				string relative = file.Remove(0, directoryPath.Length);
				m_Files.Add(new FileVersionInformation(file, relative));
			}
		}
		public SoftwareVersionInformation(Stream stream)
		{
			using (StreamReader reader = new StreamReader(stream))
			{
				m_SoftwareName = reader.ReadLine();
				m_SoftwareVersion = reader.ReadLine();
				string line = reader.ReadLine();
				while (line != null)
				{
					if (!string.IsNullOrWhiteSpace(line))
					{
						string[] parts = line.Split('\t');
						if (parts.Length == 2)
						{
							KeyValuePair<string, byte[]> pair = new KeyValuePair<string, byte[]>(parts[0], StringToByteArray(parts[1]));
							FileVersionInformation file = new FileVersionInformation(null, pair.Key, pair.Value);
							m_Files.Add(file);
						}
					}
					line = reader.ReadLine();
				}
			}
		}
		public static byte[] StringToByteArray(String hex)
		{
			int numberChars = hex.Length;
			byte[] bytes = new byte[numberChars / 2];
			for (int i = 0; i < numberChars; i += 2)
				bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
			return bytes;
		}

		public string SoftwareName { get { return m_SoftwareName; } }
		public string SoftwareVersion { get { return m_SoftwareVersion; } }

		public int Count { get { return m_Files.Count; } }
		public FileVersionInformation this[int index] { get { return m_Files[index]; } }

		public override string ToString()
		{
			return string.Format("{0} {1} ({2} files)", m_SoftwareName, m_SoftwareVersion, Count);
		}

		public void SaveManifest(string filepath)
		{
			StringBuilder builder = new StringBuilder();
			builder.AppendLine(m_SoftwareName);
			builder.AppendLine(m_SoftwareVersion);
			foreach (FileVersionInformation file in m_Files)
			{
				builder.AppendLine(file.RelativePath + "\t" + file.ToString());
			}
			File.WriteAllText(filepath, builder.ToString());
		}
	}
}
